<template>
  <div>
    <a-upload-dragger
      v-model:fileList="fileList"
      :name="name"
      @change="onChange"
      multiple
      :progress="progress"
      :action="getAction()"
      :maxCount="maxCount"
      :directory="directory"
      :accept="accept"
      :showUploadList="showUploadList"
      :headers="{
        Authorization: `Bearer ${userStore.$state.token}`,
      }"
    >
      <!-- 支持自定义插槽 -->
      <slot>
        <p>
          <inbox-outlined class="text-[32px]"></inbox-outlined>
        </p>
        <p>
          每次最多上传数量
          <a-tag>{{ maxCount || '不限' }}</a-tag>
        </p>
        <p>拖拽文件到这里进行上传</p>
      </slot>
    </a-upload-dragger>
  </div>
</template>

<script setup lang="ts">
import useSystemStore from '@/store/system';
import useUserStore from '@/store/user';
import { joinUrl } from '@/utils/file/format';
import type { UploadChangeParam, UploadFile, UploadProps } from 'ant-design-vue';

interface FileUpload {
  /* 文件上传到服务器指定的name */
  name?: string;
  /*
    最大数量,
    使用maxCount来限制单文件上传，或多文件上传
  */
  maxCount?: number;
  /* 允许上传文件夹 */
  directory?: boolean;
  /* 预览文件列表 */
  fileList?: UploadFile[];
  /* 接受的类型 */
  accept?: string;
  showUploadList?: boolean;
}
/* 文件列表,上传到本地的文件和上传到服务器的文件 */
const fileList = ref<UploadFile[]>([]);
const emit = defineEmits(['change', 'update:fileList']);
const store = useSystemStore();

withDefaults(defineProps<FileUpload>(), {
  name: 'file',
  showUploadList: true,
});
/* 自定义进度条 */
const progress: UploadProps['progress'] = {
  strokeColor: {
    '0%': 'pink',
    '100%': 'var(--primary)',
  },
  strokeWidth: 3,
  format: percent => `${parseFloat(percent!.toFixed(2))}%`,
};

const getAction = () => {
  return joinUrl(store.$state.developer.baseURL, 'common/upload');
};

const userStore = useUserStore();

/* 上传成功后，返回文件列表 */
const onChange = (info: UploadChangeParam) => {
  if (info.file.response) {
    emit('change', info.file.response);
    emit('update:fileList', fileList.value);
  }
};
</script>

<style lang="scss" scoped></style>
